package com.slfx.stock.service.impl;

import com.slfx.stock.dao.StockMapper;
import com.slfx.stock.pojo.Stock;
import com.slfx.stock.service.StockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;

@Service
public class StockServiceImpl implements StockService {

    @Autowired
    private StockMapper stockMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized int lessInventory(String goodsId, int num) {
        //先查询
//        Stock stock = stockMapper.selectByGoodsId(goodsId);
//        if (stock.getAmount() <= 0) {
//            throw new RuntimeException("库存不足");
//        }
        int i = stockMapper.lessInventory(goodsId, num);
        return i;
    }

    /**
     * synchronized在事务注解Transactional下不生效
     * @param goodsId
     * @param num
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public  synchronized int lessInventoryGetAndSet(String goodsId, int num) {
        //先查询
        Stock stock = stockMapper.selectByGoodsId(goodsId);
        if (stock.getAmount() <= 0) {
            throw new RuntimeException("库存不足");
        }
        int i = stockMapper.lessInventoryGetAndSet(goodsId, stock.getAmount()-num);
        return i;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public   int lessInventoryGetAndSet2(String goodsId, int num) {
        //先查询
        Stock stock = stockMapper.selectByGoodsIdForUpdate(goodsId);
        if (stock.getAmount() <= 0) {
            throw new RuntimeException("库存不足");
        }
        int i = stockMapper.lessInventoryGetAndSet(goodsId, stock.getAmount()-num);
        return i;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int lessInventoryByVersion(String goodsId, int num, int version) {
        return stockMapper.lessInventoryByVersion(goodsId, num, version);
    }

    @Override
    public int lessInventoryByVersionOut(String goodsId, int num) {
        return stockMapper.lessInventoryByVersionOut2(goodsId, num);
    }


}
